package com.krtech.wecard.framework.ext.filter;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.oauth2.vo.ClientSecretVo;
import com.krtech.wecard.module.pub.entity.ApplicationManagement;
import com.krtech.wecard.module.pub.service.ApplicationManagementService;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@WebFilter("/*")
@Component
public class ThirdPartFilter implements Filter {

    @Autowired
    private SysKeyValueService keyValueService;

    @Autowired
    private ApplicationManagementService applicationManagementService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;

        if ("/sys/weixin/publicNumberFocus".equals(httpServletRequest.getRequestURI())){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        if (httpServletRequest.getRequestURI().contains("/sys/user") || httpServletRequest.getRequestURI().contains("/sys/dept")){
            //判断是否参数中带有clientId和secret
            SysKeyValue globalKeyAndSecret = keyValueService.getOne(new QueryWrapper<SysKeyValue>().eq(SysKeyValue.COL_SYS_NAME, SysEnums.GLOBAL_KEY_AND_SECRET));

            String key = httpServletRequest.getHeader("key");
            String secret = httpServletRequest.getHeader("secret");
            if (StrUtil.isNotEmpty(key) && StrUtil.isNotEmpty(secret) && key.equals(globalKeyAndSecret.getSysKey()) && secret.equals(globalKeyAndSecret.getSysValue())){
                StpUtil.login(1);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }else if (StpUtil.getLoginIdByToken(httpServletRequest.getHeader("wecard")) != null){
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }else {
                throw new BusinessException("您没有权限访问当前接口");
            }
        }else if (httpServletRequest.getRequestURI().contains("/pub/notify")){
            //判断是否参数中带有clientId和secret
            //特殊处理通知
            List<ClientSecretVo> clientAndSecretList = getClientAndSecretList();

            String key = httpServletRequest.getHeader("key");
            String secret = httpServletRequest.getHeader("secret");
            if (StrUtil.isNotEmpty(key) && StrUtil.isNotEmpty(secret)){
                boolean flag = false;
                if (clientAndSecretList.size() > 0){
                    for (ClientSecretVo clientSecretVo:clientAndSecretList){
                        if (clientSecretVo.getClientId().equals(key) && clientSecretVo.getSecretId().equals(secret)){
                            flag = true;
                        }
                    }
                }

                if (flag){
                    StpUtil.login(1);
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                }else {
                    throw new BusinessException("您给定的key和secret不正确，您没有权限访问当前接口");
                }



            }else if (StpUtil.getLoginIdByToken(httpServletRequest.getHeader("wecard")) != null){
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }else {
                throw new BusinessException("您没有权限访问当前接口");
            }
        }else {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }


    public List<ClientSecretVo> getClientAndSecretList(){
        List<ApplicationManagement> list = applicationManagementService.list();

        List<ClientSecretVo> applicationClientSecretList = new ArrayList<>();

        if (list.size() > 0){
            applicationClientSecretList = list.stream().map(applicationManagement -> {
                ClientSecretVo clientSecretVo = new ClientSecretVo();
                clientSecretVo.setClientId(applicationManagement.getAppKey());
                clientSecretVo.setSecretId(applicationManagement.getAppSecret());
                return clientSecretVo;
            }).collect(Collectors.toList());
        }


        SysKeyValue globalKeyAndSecret = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, SysEnums.GLOBAL_KEY_AND_SECRET));

        if (globalKeyAndSecret != null){
            ClientSecretVo clientSecretVo = new ClientSecretVo();
            clientSecretVo.setClientId(globalKeyAndSecret.getSysKey());
            clientSecretVo.setSecretId(globalKeyAndSecret.getSysValue());
            applicationClientSecretList.add(clientSecretVo);
        }

        return applicationClientSecretList;
    }
}
